<template>
  <div class="login-bg">
    <div class="login-wrapper">
      <el-card class="login-card" shadow="always">
        <div class="login-title">DNS-Radar</div>
        <el-tabs v-model="activeTab" stretch>
          <el-tab-pane label="登录" name="login">
            <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="0">
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" placeholder="用户名" clearable />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="密码" show-password clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" style="width:100%" size="large" @click="handleLogin" :loading="loginLoading">
                  {{ loginLoading ? '登录中...' : '登录' }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="注册" name="register">
            <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="0">
              <el-form-item prop="username">
                <el-input v-model="registerForm.username" placeholder="用户名" clearable />
              </el-form-item>
              <el-form-item prop="email">
                <el-input v-model="registerForm.email" placeholder="邮箱" clearable />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="密码" show-password clearable />
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" show-password clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" style="width:100%" size="large" @click="handleRegister" :loading="registerLoading">
                  {{ registerLoading ? '注册中...' : '注册' }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
import authApi from '@/api/auth';
import { auth } from '@/utils/auth';

const router = useRouter();
const activeTab = ref('login');

// 检查是否已登录
onMounted(() => {
  if (auth.isAuthenticated()) {
    router.push('/dashboard');
  }
});

// 登录表单
const loginForm = ref({
  username: '',
  password: ''
});
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
const loginFormRef = ref(null);

// 登录加载状态
const loginLoading = ref(false);

// 处理登录
const handleLogin = async () => {
  try {
    const valid = await loginFormRef.value.validate();
    if (!valid) {
      ElMessage.error('请填写完整信息');
      return;
    }

    loginLoading.value = true;

    const response = await authApi.login({
      username: loginForm.value.username,
      password: loginForm.value.password
    });

    if (response.code === 200) {
      // 登录成功
      auth.login(response.data.token, response.data.user);
      ElMessage.success(response.message || '登录成功');
      
      // 获取重定向路径，如果没有则跳转到仪表盘
      const redirect = router.currentRoute.value.query.redirect || '/dashboard';
      router.push(redirect);
    } else {
      ElMessage.error(response.message || '登录失败');
    }
  } catch (error) {
    console.error('登录错误:', error);
    ElMessage.error(error.message || '登录失败，请稍后重试');
  } finally {
    loginLoading.value = false;
  }
};

// 注册表单
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
});
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度必须在3-50字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};
const registerFormRef = ref(null);

// 注册加载状态
const registerLoading = ref(false);

// 处理注册
const handleRegister = async () => {
  try {
    const valid = await registerFormRef.value.validate();
    if (!valid) {
      ElMessage.error('请填写完整信息');
      return;
    }

    registerLoading.value = true;

    const response = await authApi.register({
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password,
      confirmPassword: registerForm.value.confirmPassword
    });

    if (response.code === 200) {
      ElMessage.success(response.message || '注册成功');
      // 注册成功后切换到登录标签
      activeTab.value = 'login';
      // 清空注册表单
      registerForm.value = {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      };
    } else {
      ElMessage.error(response.message || '注册失败');
    }
  } catch (error) {
    console.error('注册错误:', error);
    ElMessage.error(error.message || '注册失败，请稍后重试');
  } finally {
    registerLoading.value = false;
  }
};


</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-wrapper {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  width: 380px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  padding: 36px 32px 28px 32px;
  background: rgba(255,255,255,0.98);
}
.login-title {
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 28px;
  color: #409eff;
  letter-spacing: 2px;
}
.el-tabs__item {
  font-size: 18px;
}
.el-form-item {
  margin-bottom: 24px;
}
</style>